package com.loadburn.heron.complier.tags;

import com.loadburn.heron.cache.WebCache;
import com.loadburn.heron.config.GlobalConfig;
import com.loadburn.heron.template.Template;
import com.loadburn.heron.utils.TemplateUtils;
import org.apache.commons.io.IOUtils;
import org.mvel2.MVEL;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.templates.TemplateError;
import org.mvel2.templates.TemplateRuntime;
import org.mvel2.templates.res.Node;
import org.mvel2.templates.util.TemplateOutputStream;

import java.io.*;
import java.util.Map;

import static org.mvel2.templates.util.TemplateTools.captureToEOS;
import static org.mvel2.templates.util.TemplateTools.readInFile;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 13-12-26
 */
public class IncludeCacheNode extends Node {

    WebCache templateCache;

    int includeStart;
    int includeOffset;

    int preStart;
    int preOffset;

    public IncludeCacheNode(WebCache templateCache, int begin, String name,
                            char[] template, int start, int end) {

        this.templateCache = templateCache;
        this.begin = begin;
        this.name = name;
        this.contents = template;
        this.cStart = start;
        this.cEnd = end - 1;
        this.end = end;

        int mark = captureToEOS(contents, 0);
        includeStart = cStart;
        includeOffset = mark - cStart;
        preStart = ++mark;
        preOffset = cEnd - mark;

    }

    public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) {
        String file = MVEL.eval(contents, includeStart, includeOffset, ctx, factory, String.class);

        if (preOffset != 0) {
            MVEL.eval(contents, preStart, preOffset, ctx, factory);
        }

        String text = null;
        String tmpFileName = file;
        if (tmpFileName.charAt(0) != IOUtils.DIR_SEPARATOR_UNIX) {
            tmpFileName = IOUtils.DIR_SEPARATOR_UNIX + tmpFileName;
        }
        Map<String, Template> templateMap = (Map<String, Template>) templateCache.get(Template.WEB_TEMPLATE);
        if (templateMap != null) {
            Template template = templateMap.get(tmpFileName);
            if (template != null) {
                text = template.getText();
            }
        }

        if (text == null) {

            Template template = new TemplateUtils(GlobalConfig.getWebViewSuffix()).
                    inOneOfFullPath(String.valueOf(runtime.getRelPath().peek()), tmpFileName);
            if (template != null) {
                text = template.getText();
            }
        }

        if (text == null) {
            text = readInFile(runtime, file);
        }

        if (next != null) {
            return next.eval(runtime, appender.append(String.valueOf(TemplateRuntime.eval(text, ctx, factory))), ctx, factory);
        } else {
            return appender.append(String.valueOf(MVEL.eval(text, ctx, factory)));
        }
    }

    public boolean demarcate(Node terminatingNode, char[] template) {
        return false;
    }


    public static String readInFile(TemplateRuntime runtime, String fileName) {


        File file = new File(String.valueOf(runtime.getRelPath().peek()) + "/" + fileName);

        try {
            FileInputStream instream = new FileInputStream(file);
            BufferedInputStream bufstream = new BufferedInputStream(instream);

            runtime.getRelPath().push(file.getParent());

            byte[] buf = new byte[10];
            int read;
            int i;

            StringBuilder appender = new StringBuilder();

            while ((read = bufstream.read(buf)) != -1) {
                for (i = 0; i < read; i++) {
                    appender.append((char) buf[i]);
                }
            }

            bufstream.close();
            instream.close();

            runtime.getRelPath().pop();

            return appender.toString();

        } catch (FileNotFoundException e) {
            throw new TemplateError("cannot include template '" + fileName + "': file not found.");
        } catch (IOException e) {
            throw new TemplateError("unknown I/O exception while including '" + fileName + "' (stacktrace nested)", e);
        }
    }
}